/**
 * Copyright (c) 2019-2029, wwww.kiwipeach.cn (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cn.kiwipeach.testcase.thread;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * 参考博客链接：https://www.cnblogs.com/xzmxddx/p/10362810.html
 * 1）主线程等待：
 * while (cw.value == null){
 * Thread.currentThread().sleep(100);
 * }
 * 2）t.join();方法等待子线程执行结束
 * 3）
 *
 * @author kiwipeach
 * @since 2.0
 */
@Slf4j
public class 测试多线程获取返回值 {

    class MyCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            log.info("开始执行线程...");
            //Thread.currentThread().sleep(5000);
            log.info("线程执行完毕...");
            return String.format("线程名称:%s", Thread.currentThread().getName());
        }
    }

    @Test
    public void 线程池中获取返回值() throws InterruptedException {
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        Future<String> future = newCachedThreadPool.submit(new MyCallable());
        try {
            log.info("执行状态1：是否完成？({})， 是否取消？({}), ", future.isDone(), future.isCancelled());
            if (false) {
                future.cancel(true);
            }
            log.info("执行状态2：是否完成？({})， 是否取消？({}), ", future.isDone(), future.isCancelled());
            //log.info("获取到返回值：{}", future.isDone() ? "已完成无法获取线程返回值" : future.get());
            log.info("获取到返回值：{}", future.isDone() ? "已完成无法获取线程返回值" : future.get(2, TimeUnit.SECONDS));
            log.info("执行状态3：是否完成？({})， 是否取消？({}), ", future.isDone(), future.isCancelled());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            newCachedThreadPool.shutdown();
        }
        Thread.sleep(100000);
    }
}
